package com.pn.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pn.dto.AssignAuthDto;
import com.pn.dto.RolePageList;
import com.pn.entity.Auth;
import com.pn.entity.Role;
import com.pn.mapper.RoleMapper;
import com.pn.service.RoleService;
import com.pn.utils.PageBean;
import com.pn.utils.Result;
import com.pn.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


//指定缓存的名称（就是缓存的前缀），一般是标注@CacheConfig注解类的全路径
@CacheConfig(cacheNames = "com.pn.controller.AuthInfoController")
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    //查询所有角色
    @Override
    public List<Role> roleList() {
        List<Role> roleList= roleMapper.roleList();
        return roleList;
    }

    //查询用户已分配的角色
    @Override
    public List<Role> userRoleList(Integer userId) {
        List<Role> roleList = roleMapper.userRoleList(userId);

        return roleList;
    }

    //角色列表
    @Override
    public PageBean<Role> rolePageList(RolePageList rolePageList) {
        PageHelper.startPage(rolePageList.getPageNum(),rolePageList.getPageSize());
        Page<Role> page = roleMapper.rolePageList(rolePageList);
        long total = page.getTotal();
        List<Role> result = page.getResult();
        return new PageBean(total,result);
    }

    //添加角色
    @Override
    public Result roleAdd(Role role) {
        //先查询有没有一样的角色名
        List<Role> list = roleMapper.roleByRoleName(role.getRoleName(),role.getRoleCode());
        if(list != null && list.size() > 0){
            //查到了则返回角色已存在
            return Result.err(Result.CODE_ERR_BUSINESS,"角色已存在");
        }
        Map<String,Object> map =(Map<String, Object>) ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("userId");
        role.setRoleState("0");
        role.setCreateBy(userId);
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateBy(userId);
        int j = roleMapper.roleAdd(role);
        if(j > 0){
            return Result.ok("角色添加成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"角色添加失败");
    }

    //启用禁用角色
    @Override
    public Result roleStateUpdateByRid(Role role) {
        int i = roleMapper.roleStateUpdateByRid(role);
        if(i > 0 ){
            return Result.ok("启用禁用角色成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"启用禁用角色失败");
    }

    //删除角色
    @Transactional
    @Override
    public Result roleDeleteByRid(Integer roleId) {
        //根据角色id删除角色
        roleMapper.roleDeleteByRid(roleId);
        //根据角色id删除角色权限的关联表
        roleMapper.roleAuthDeleteByRid(roleId);
        return Result.ok("角色删除成功");
    }

    //获取权限列表
    @Override
    //查询方法上标注@Cacheable注解并指定缓存的键
    //@Cacheable(key = "'all:authTree'")
    public List<Auth> roleAuthTree() {
        List<Auth> authList = roleMapper.roleAuthTree();
        List<Auth> authTreeList = UserServiceImpl.allAuthToAuthTree(authList, 0);
        return authTreeList;

    }

    //根据角色id查询分配的所有权限菜单的方法
    @Override
    public List<Integer> querRoleAuthIds(Integer roleId) {
        return roleMapper.findAuthByRid(roleId);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //给角色添加权限
    @Transactional
    @Override
    public Result grantAuthAdd(AssignAuthDto assignAuthDto) {
        //根据roleId删除角色权限表
        roleMapper.roleAuthDeleteByRid(assignAuthDto.getRoleId());
        //插入
        List<Integer> authIds = assignAuthDto.getAuthIds();
        for (Integer authId : authIds) {
            roleMapper.grantAuthAdd(assignAuthDto.getRoleId(),authId);
        }

        //删除redis中关于用户的权限
        stringRedisTemplate.delete(stringRedisTemplate.keys("authTree:"+"*"));
        return Result.ok("添加成功");
    }

    //修改角色
    public Result setDescByRid(Role role){
        Map<String,Object> map =(Map<String, Object>) ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("userId");

        role.setCreateBy(userId);
        role.setCreateTime(LocalDateTime.now());

        int i = roleMapper.setDescByRid(role);
        if (i>0){
            return Result.ok("修改角色成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"修改角色失败");
    }




}
